package com.dp.appi.dao.impl;

import com.dp.appi.dao.FavoriteDao;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaoji on 2016/4/29.
 */
@Component
public class FavoriteDaoImpl extends BaseDaoImpl implements FavoriteDao {

    /**
     * 获取收藏列表
     *
     * @param name 百科名称
     * @param s    开始序列
     * @param n    获取条数
     * @param id   登录用户id
     * @return
     */
    @Override
    public List<Map<String, Object>> collectList(String name, Integer s, Integer n, String id) {
        String sql="select ef.favorite_id,ef.encyclopedia_id,tsbu.realname as author,ee.title,ee.article_thumb,UNIX_TIMESTAMP(ef.create_time) create_time" +
                " from e_favorite ef" +
                " LEFT JOIN e_encyclopedia ee on ef.encyclopedia_id=ee.encyclopedia_id" +
                " LEFT JOIN t_s_base_user tsbu on tsbu.ID = ee.author" +
                " where ef.user_id=? ";
        if(!StringUtils.isEmpty(name)){
            name=name.replace(" ","%");
            sql+=" and ee.title like '%"+name+"%'";
        }
        sql+=" ORDER BY ef.create_time desc limit ?,?";
        return getJdbcTemplate().queryForList(sql,new Object[]{id,s,n});
    }

    /**
     * 用户收藏百科
     *
     * @param encyclopedia_id 百科文章id
     * @param id              登录用户id
     */
    @Override
     public Long addCollect(Long encyclopedia_id, String id) {
        String sql="insert into e_favorite(encyclopedia_id,user_id,create_time) " +
                "values(:encyclopedia_id,:id,NOW())";
//        getJdbcTemplate().update(sql,new Object[]{encyclopedia_id,id});
        Map map = new HashMap();
        map.put("encyclopedia_id",encyclopedia_id);
        map.put("id",id);
        return this.executeSqlReturnKey(sql,map);
    }

    /**
     * 删除百科收藏
     *
     * @param favorite_id 收藏id
     * @param id              登录用户id
     */
    @Override
    public void delCollect(Long favorite_id, String id) {
        String sql="delete from e_favorite where favorite_id=? and user_id=?";
        getJdbcTemplate().update(sql,new Object[]{favorite_id,id});
    }

    /**
     * 获取收藏的百科
     *
     * @param encyclopedia_id
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getCollect(Long encyclopedia_id, String id) {
        StringBuffer sql = new StringBuffer();
        sql.append("select * from e_favorite where user_id = ? and encyclopedia_id = ?");
        return findOneForJdbc(sql.toString(),id,encyclopedia_id);
    }
}
